package banmuoi.servlet;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.Session;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import banmuoi.entity.Admin;
import banmuoi.util.HibernateUtil;
import banmuoi.util.WebUtil;

@Results(value={
		@Result(name="input", location="/admin/WebMaster.jsp"),
		@Result(name="signin", location="/admin/index.jsp"),
		@Result(name="new", type="redirectAction", params={"actionName", "inputWebMaster"})
	})
public class AdminAction extends SecurityAction implements ModelDriven<Admin>{
	Session session = HibernateUtil.openSession();
	ActionSupport acsup = new ActionSupport();
	Admin model = new Admin();
	@Override
	public Admin getModel() {
		// TODO Auto-generated method stub
		return model;
	}
	
	@Action(value="/signin")
	public String signin() throws Exception {
		if(model.getId() != null){
			try {
				String password = model.getPassword();
				session.refresh(model);
				
				if(!password.equals(model.getPassword())){
					acsup.addActionMessage("Invalid password !");
				}
				else {
					WebUtil.setSession("admin", model);
					
					String returnUrl = (String) WebUtil.getSession("returnUrl");
					if(returnUrl != null){
						WebUtil.sendRedirect(returnUrl);
					}
					else{
						acsup.addActionMessage("Login successfully !");
					}
				}
			} catch (Exception e) {
				acsup.addActionMessage("Invalid user name !");
			}
		}
		return "signin";
	}
	
	
}
